package com.quanquan.store.service.marketActivity;

import DTO.PageDTO;
import DTO.user.UserDTO;
import DTO.user.UserInfoDTO;
import com.quanquan.store.dto.IdDTO;
import com.quanquan.store.entity.marketActivity.paperPlane.PaperPlane;
import com.quanquan.store.entity.marketActivity.paperPlane.PaperPlaneCode;
import com.quanquan.store.entity.marketActivity.paperPlane.PaperPlaneGift;
import com.quanquan.store.entity.marketActivity.paperPlane.PaperPlaneRecord;
import com.quanquan.store.repository.marketActivity.paperPlane.PaperPlaneCodeRepository;
import com.quanquan.store.repository.marketActivity.paperPlane.PaperPlaneGiftRepository;
import com.quanquan.store.repository.marketActivity.paperPlane.PaperPlaneRecordRepository;
import com.quanquan.store.repository.marketActivity.paperPlane.PaperPlaneRepository;
import com.quanquan.store.request.marketActivity.PaperPlaneRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import utils.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName PaperPlaneService
 * @Description
 * @Author Owen
 * @Date 2019/9/17 0017 下午 2:30
 * @Version V1.0
 **/
@Service
@Slf4j
public class PaperPlaneService {

    @Autowired
    private PaperPlaneCodeRepository paperPlaneCodeRepository;

    @Autowired
    private PaperPlaneRepository paperPlaneRepository;

    @Autowired
    private PaperPlaneRecordRepository paperPlaneRecordRepository;

    @Autowired
    private PaperPlaneGiftRepository paperPlaneGiftRepository;

    @Autowired
    private RestTemplate restTemplate;


    public PaperPlane getById(Long id){
        PaperPlane paperPlane = paperPlaneRepository.findById(id).orElse(null);
        return paperPlane;
    }


    /**
     * 根据码查询
     * @param planeCode
     * @return
     */
    public PaperPlaneCode getByCodeAndActivityId(String planeCode, Long activityId){
        PaperPlaneCode paperPlaneCode = paperPlaneCodeRepository.findByCodeAndActivityId(planeCode,activityId);
        return paperPlaneCode;
    }

    public PaperPlaneCode savePlaneCode(PaperPlaneCode paperPlaneCode){
        paperPlaneCode = paperPlaneCodeRepository.saveAndFlush(paperPlaneCode);
        return paperPlaneCode;
    }

    /**
     * 管理后台获取活动列表
     * @param request
     * @return
     */
    public PageDTO findAllPlaneByPage(PaperPlaneRequest request){
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = PageRequest.of(request.getPage(),request.getSize(),sort);

        Page<PaperPlane> all = paperPlaneRepository.findAll((Specification<PaperPlane>) (root, query, criteriaBuilder)->{
            Predicate conditions = criteriaBuilder.conjunction();
            conditions = criteriaBuilder.and(criteriaBuilder.notEqual(root.get("status").as(Integer.class),2));
            if(StringUtils.isNotEmpty(request.getKeyword())){
                Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%" + request.getKeyword() + "%");
                conditions = criteriaBuilder.and(conditions,p1);
            }
            return query.where(conditions).getRestriction();
        }, pageable);
        PageDTO<PaperPlane> pageDTO = new PageDTO<>();
        pageDTO.setTotal(all.getTotalElements());
        pageDTO.setList(all.getContent());
        pageDTO.setTotalPage(all.getTotalPages());
        pageDTO.setPage(request.getPage());
        pageDTO.setPageSize(request.getSize());
        pageDTO.setKeyword(request.getKeyword());
        return pageDTO;
    }

    /**
     * 管理后台获取所有刮刮卡活动列表
     * @param request
     * @return
     */
    public PageDTO findAllPlaneCodeByPage(PaperPlaneRequest request){
        Sort sort = new Sort(Sort.Direction.DESC,"joinTime");
        Pageable pageable = PageRequest.of(request.getPage(),request.getSize(),sort);

        Page<PaperPlaneCode> all = paperPlaneCodeRepository.findAll((Specification<PaperPlaneCode>) (root, query, criteriaBuilder)->{
            Predicate conditions = criteriaBuilder.conjunction();
            conditions = criteriaBuilder.and(criteriaBuilder.equal(root.get("activityId").as(Long.class),request.getActivityId()));
            conditions = criteriaBuilder.and(conditions,criteriaBuilder.notEqual(root.get("status").as(Integer.class),0));
            if(StringUtils.isNotEmpty(request.getKeyword())){
                Predicate p1 = criteriaBuilder.like(root.get("code").as(String.class), "%" + request.getKeyword() + "%");
                conditions = criteriaBuilder.and(conditions,p1);
            }
            return query.where(conditions).getRestriction();
        }, pageable);
        PageDTO<PaperPlaneCode> pageDTO = new PageDTO<>();
        pageDTO.setTotal(all.getTotalElements());

        List<PaperPlaneCode> list = all.getContent();
        for (int i = 0; i < list.size(); i++) {
            IdDTO idDTO = new IdDTO();
            List<String> ids = new LinkedList<>();
            ids.add(list.get(i).getUserId());
            idDTO.setForeignKeyIds(ids);

            UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
            if(null == userInfoDTO || userInfoDTO.getUserDTOS().size() < 1){
                continue;
            }
            UserDTO userDTO = userInfoDTO.getUserDTOS().get(0);
            if(null == userDTO){
                continue;
            }
            list.get(i).setUserPhone(userDTO.getPhone());
            log.info(list.get(i).getUserPhone());
        }

        pageDTO.setList(list);
        pageDTO.setTotalPage(all.getTotalPages());
        pageDTO.setPage(request.getPage());
        pageDTO.setPageSize(request.getSize());
        pageDTO.setKeyword(request.getKeyword());
        return pageDTO;
    }


    public List<PaperPlaneRecord> getPaperPlaneRecordList(Long activityId){
        List<PaperPlaneRecord> list = paperPlaneRecordRepository.findAllByActivityId(activityId);
        return list;
    }

    public int sumGiftCountByUserIdAndCouponId(Long activityId,String userId,String couponId){
        return paperPlaneRecordRepository.sumGiftCount(activityId,userId,couponId);
    }

    public int countByStatus(Long activityId,Integer status){
        int count = paperPlaneCodeRepository.countByStatus(activityId,status);
        return count;
    }

    public List<String> getUserIdByDifficulty(Long activityId,Integer difficulty){
        return paperPlaneCodeRepository.findByDifficulty(activityId,difficulty);
    }

    public List<PaperPlaneGift> getGiftListByDifficulty(Long activityId, Integer difficulty){
        return paperPlaneGiftRepository.findAllByActivityIdAndDifficultyAndStatusAndStartTimeBeforeAndEndTimeAfterAndRemainTotalGreaterThan(activityId,difficulty,1,new Date(),new Date(),0);
    }

    public PaperPlaneRecord saveOrUpdateRecord(PaperPlaneRecord record){
        return paperPlaneRecordRepository.saveAndFlush(record);
    }

    public int substractStock(Long giftId,Integer subNum){
        return paperPlaneGiftRepository.substractStock(giftId,subNum);
    }
}
